package com.shenhua.kunpeng.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.shenhua.kunpeng.dto.FillUserDTO;
import com.shenhua.kunpeng.utils.FillUserDTOContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

public class MyMetaObjectHandler implements MetaObjectHandler {
  @Override
  public void insertFill(MetaObject metaObject) {
    FillUserDTO fillUserDTO = FillUserDTOContextHolder.get();
    if (fillUserDTO != null) {
      if (!StringUtils.isEmpty(fillUserDTO.getUserId())) {
        this.strictInsertFill(
            metaObject, "createBy", String.class, fillUserDTO.getUserId().toString());
        this.strictInsertFill(
            metaObject, "modifiedBy", String.class, fillUserDTO.getUserId().toString());
      } else {
        this.strictInsertFill(metaObject, "createBy", String.class, "");
        this.strictInsertFill(metaObject, "modifiedBy", String.class, "");
      }
      if (!StringUtils.isEmpty(fillUserDTO.getRealName())) {
        this.strictInsertFill(metaObject, "createName", String.class, fillUserDTO.getRealName());
        this.strictInsertFill(metaObject, "modifiedName", String.class, fillUserDTO.getRealName());
      } else {
        this.strictInsertFill(metaObject, "createName", String.class, "");
        this.strictInsertFill(metaObject, "modifiedName", String.class, "");
      }
    }

    this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "lastModifiedTime", LocalDateTime.class, LocalDateTime.now());
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    FillUserDTO fillUserDTO = FillUserDTOContextHolder.get();
    if (fillUserDTO != null) {
      if (!StringUtils.isEmpty(fillUserDTO.getUserId())) {
        this.strictInsertFill(
            metaObject, "modifiedBy", String.class, fillUserDTO.getUserId().toString());
      } else {
        this.strictInsertFill(metaObject, "modifiedBy", String.class, "");
      }
      if (!StringUtils.isEmpty(fillUserDTO.getRealName())) {
        this.strictInsertFill(metaObject, "modifiedName", String.class, fillUserDTO.getRealName());
      } else {
        this.strictInsertFill(metaObject, "modifiedName", String.class, "");
      }
    }
    this.strictInsertFill(metaObject, "lastModifiedTime", LocalDateTime.class, LocalDateTime.now());
  }
}
